
#include "account_sem.h"

#include <stdio.h>
#include <pthread.h>

typedef struct
{
    Account *account;
    char name[20];
    double amt;
} OperArg;

void *withdraw_th_func(void *arg)
{
    OperArg *oa = (OperArg *)arg;
    double amt = withdraw(oa->account, oa->amt);

    printf("%8s(0x%lx) withdraw %f from account %d\n",
           oa->name, pthread_self(), amt, oa->account->code);

    return (void *)0;
}

/**
 * 模拟同一时刻，两个人对同一帐号的取款行为
 *  账户只有10000元，正常结果应该是只有一个人取款正常而非2个人都取到10000元，
 */
int main()
{

    pthread_t girl, boy;

    Account *account = create_account(1000001, 10000);
    OperArg oa_gril = {account, "girl", 10000};
    OperArg oa_boy = {account, "boy", 10000};

    if (pthread_create(&girl, NULL, withdraw_th_func, &oa_gril) != 0)
    {
        perror("pthread_create error!");
    }

    if (pthread_create(&boy, NULL, withdraw_th_func, &oa_boy) != 0)
    {
        perror("pthread_create error!");
    }

    pthread_join(girl, NULL);
    pthread_join(boy, NULL);


    return 0;
}